package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public  void  testLockMethod() {
        RLock lock = redissonClient.getLock("lock");//只要锁名称相同就是同一把锁
        lock.lock(1,TimeUnit.SECONDS);//上锁了

        Integer num = (Integer) redisTemplate.opsForValue().get("num");
        if(!StringUtils.isEmpty(num)){
            num++;
            redisTemplate.opsForValue().set("num",num);
        }

        lock.unlock();//解锁


    }
    //使用尝试加锁
    public void testTryLockMethod() {
        RLock lock = redissonClient.getLock("lock");//可重入锁
        try {
            boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if(res){
                Integer num = (Integer) redisTemplate.opsForValue().get("num");
                if(!StringUtils.isEmpty(num)){
                    num++;
                    redisTemplate.opsForValue().set("num",num);
                }
            }else {
                Thread.sleep(1000);
                testReadMethod();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public Object testReadMethod() {
        //初始化读锁  读锁是10秒  此10秒之内 随时可以读取  但不可以写
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        readWriteLock.readLock().lock(10,TimeUnit.SECONDS);

        return redisTemplate.opsForValue().get("msg");


    }
    public Object testWriteMethod() {
        //初始化写锁 写锁是10秒  此10秒之内 不可以读也不可以写
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        readWriteLock.writeLock().lock(10,TimeUnit.SECONDS);

         redisTemplate.opsForValue().set("msg",UUID.randomUUID().toString());

        return "写入成功...";
    }
//    @Override
//    public  synchronized void  testLockMethod() {
//        Integer num = (Integer) redisTemplate.opsForValue().get("num");
//        if(!StringUtils.isEmpty(num)){
//            num++;
//            redisTemplate.opsForValue().set("num",num);
//        }
//    }
}
